/**
 * Jest测试环境设置
 * 配置测试数据库和全局测试环境
 */

import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';
import { config } from '../src/config';

// 全局变量声明
declare global {
  var __MONGO_URI__: string;
  var __MONGO_DB_NAME__: string;
}

let mongod: MongoMemoryServer;

/**
 * 在所有测试开始前设置测试环境
 */
beforeAll(async () => {
  try {
    // 启动内存MongoDB服务器
    mongod = await MongoMemoryServer.create({
      instance: {
        dbName: 'test-user-permission-db',
      },
    });

    // 获取连接URI
    const uri = mongod.getUri();
    global.__MONGO_URI__ = uri;
    global.__MONGO_DB_NAME__ = 'test-user-permission-db';

    // 连接到测试数据库
    await mongoose.connect(uri, {
      dbName: 'test-user-permission-db',
    });
    
    console.log('✅ Test database connected');
  } catch (error) {
    console.error('❌ Failed to setup test database:', error);
    throw error;
  }
});

/**
 * 每个测试后清理数据
 */
afterEach(async () => {
  try {
    // 清理所有集合的数据
    const collections = mongoose.connection.collections;
    for (const key in collections) {
      const collection = collections[key];
      await collection.deleteMany({});
    }
  } catch (error) {
    console.error('❌ Failed to cleanup test data:', error);
  }
});

/**
 * 所有测试结束后清理环境
 */
afterAll(async () => {
  try {
    // 断开数据库连接
    await mongoose.connection.dropDatabase();
    await mongoose.connection.close();

    // 停止内存MongoDB服务器
    if (mongod) {
      await mongod.stop();
    }

    console.log('✅ Test environment cleaned up');
  } catch (error) {
    console.error('❌ Failed to cleanup test environment:', error);
  }
});

/**
 * 设置测试超时
 */
jest.setTimeout(30000);

/**
 * 禁用控制台输出（可选）
 */
if (process.env.NODE_ENV === 'test') {
  console.log = jest.fn();
  console.error = jest.fn();
  console.warn = jest.fn();
}
